﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Text.RegularExpressions;
using System.Xml;

using System.Collections;
using System.IO;
using System.IO.Compression;
using System.Runtime.Serialization.Formatters.Binary;
using System.Xml.Serialization;



public class Common2
{
    /// <summary>
    /// 修改数据集
    /// </summary>
    /// <param name="dt">数据源</param>
    /// <param name="field">请求字段</param>
    /// <param name="key">主键值</param>
    /// <param name="value">值</param>
    /// <returns></returns>
    public static DataTable ChangeDataTable(DataTable dt, string field, string key, string value)
    {
        //规格
        if ("sl" == field)
        {
            foreach (DataRow dr in dt.Rows)
            {
                if (dr["cpbh"].ToString() == key)
                {
                    dr.BeginEdit();
                    dr[field] = value;//数量改变
                    dr["xj"] = MultNumber(decimal.Parse(value), decimal.Parse(dr["dj"].ToString()));//小计改变
                    dr.EndEdit();
                }
            }
        }
        return dt;
    }
    public static string MultNumber(decimal num, decimal dj)
    {
        decimal number = num * dj;
        return number.ToString("0.00");
    }
    /// <summary>

    /// 字符串截取方法

    /// </summary>

    /// <param name="str">截取字符</param>

    /// <param name="len">大于Len时,截取len</param>

    /// <returns></returns>

    public static string Substr(string str, int len)
    {

        if (!string.IsNullOrEmpty(str))
        {

            System.Text.RegularExpressions.Regex rChinese = new Regex(@"[\u4e00-\u9fa5]"); //验证中文

            Regex rEnglish = new Regex(@"^[A-Za-z0-9]+$"); //验证字母

            if (rChinese.IsMatch(str))
            {
                //中文
                return (str.Length > len) ? str.Substring(0, len) + "..." : str;

            }

            else if (rEnglish.IsMatch(str))
            {
                //英文
                return (str.Length > len * 2) ? str.Substring(0, len * 2) + "..." : str;
            }
            return (str.Length > len) ? str.Substring(0, len) + "..." : str;

        }

        return "";

    }
    public static string CutString(int start, int end, string str)
    {

        if (!string.IsNullOrEmpty(str))
        {

            Regex rChinese = new Regex(@"[\u4e00-\u9fa5]"); //验证中文

            Regex rEnglish = new Regex(@"^[A-Za-z0-9]+$"); //验证字母

            if (rChinese.IsMatch(str))
            {
                str = str.Substring(start, end);
            }

            else if (rEnglish.IsMatch(str))
            {
                str = str.Substring(start, end * 2);
            }
        }
        return str;
    }

    public static List<string> ArrayString(string str, int len)
    {
        List<string> strList = new List<string>();

        int start = 0;
        int end = start + len;

        while (true)
        {
            if (start >= str.Length)
                return strList;
            string temp = CutString(start, end, str);
            strList.Add(temp);
            start = end;
            end = end + 6;
            if (end >= str.Length)
            {
                end = str.Length;
            }
        }
    }

    #region XML 文件操作
    public ConfigModel GetXml()
    {
        ConfigModel model = new ConfigModel();
        XmlDocument doc = new XmlDocument();
        string path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase) + @"\config.xml";
        doc.Load(path);    //加载Xml文件  
        XmlElement rootElem = doc.DocumentElement;   //获取根节点  
        XmlNodeList InfoXmls = rootElem.ChildNodes;//继续获取  根节点 所有的子节点

        foreach (XmlNode xn1 in InfoXmls)//遍历
        {
            XmlElement xe = (XmlElement)xn1;//将子节点类型转换为XmlElement类型
            if (xe.GetAttribute("DatabaseName") == "Source")// 查找源数据库节点
            {
                XmlNodeList nls = xe.ChildNodes;
                foreach (XmlNode xnn1 in nls)
                {
                    XmlElement childxe = (XmlElement)xnn1;
                    if (childxe.Name == "Server")
                    {
                        model.Server = childxe.InnerText;
                    }
                    else if (childxe.Name == "Account")
                    {
                        model.UserName = childxe.InnerText;
                    }
                    else if (childxe.Name == "PassWord")
                    {
                        model.PassWord = childxe.InnerText;
                    }
                    else if (childxe.Name == "Directory")
                    {
                        model.Directory = childxe.InnerText;
                    }
                    else if (childxe.Name == "DatabaseName")
                    {
                        model.DataBase = childxe.InnerText;
                    }
                    else if (childxe.Name == "WebService")
                    {
                        model.WebService = childxe.InnerText;
                    }
                    else if (childxe.Name == "FormText")
                    {
                        model.FormText = childxe.InnerText;
                    }
                    else if (childxe.Name == "ServerType")
                    {
                        model.ServerType = childxe.InnerText;
                    }

                    else if (childxe.Name == "ServerType2")
                    {
                        model.ServerType2 = childxe.InnerText;
                    }


                }
            }
            else if (xe.GetAttribute("DatabaseName") == "Target")
            {
                XmlNodeList nls = xe.ChildNodes;
                foreach (XmlNode xnn1 in nls)
                {
                    XmlElement childxe = (XmlElement)xnn1;
                    if (childxe.Name == "Server")
                    {
                        model.Server2 = childxe.InnerText;
                    }
                    else if (childxe.Name == "Account")
                    {
                        model.UserName2 = childxe.InnerText;
                    }
                    else if (childxe.Name == "PassWord")
                    {
                        model.PassWord2 = childxe.InnerText;
                    }

                    else if (childxe.Name == "DatabaseName")
                    {
                        model.DataBase2 = childxe.InnerText;
                    }
                }
            }
        }
        return model;
    }
    public void SetXml(string noteName, string value, string noteType)
    {
        XmlDocument doc = new XmlDocument();
        string path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase) + @"\config.xml";
        doc.Load(path);    //加载Xml文件  
        XmlElement rootElem = doc.DocumentElement;   //获取根节点  

        XmlNodeList InfoXmls = rootElem.ChildNodes;//继续获取  根节点 所有的子节点

        foreach (XmlNode xn1 in InfoXmls)//遍历
        {
            XmlElement xe = (XmlElement)xn1;//将子节点类型转换为XmlElement类型
            if (xe.GetAttribute("DatabaseName") == noteType)// 查找源数据库节点
            {
                XmlNodeList nls = xe.ChildNodes;
                foreach (XmlNode xnn1 in nls)
                {

                    XmlElement childxe = (XmlElement)xnn1;

                    if (childxe.Name == noteName)
                    {
                        childxe.InnerText = value;
                    }
                }
            }

        }
        doc.Save("config.xml");
    }
    public int GetSystemInfo(string name, ref string value)
    {
        int status = 0;
        try
        {
            XmlDocument doc = new XmlDocument();
            string path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase) + @"\config.xml";
            doc.Load(path);    //加载Xml文件  
            XmlElement rootElem = doc.DocumentElement;   //获取根节点  

            XmlNodeList personNodes = rootElem.GetElementsByTagName("UploadInfo"); //获取PrintInfo 子节点集合  

            foreach (XmlNode node in personNodes)
            {
                XmlElement xe = (XmlElement)node;//将子节点类型转换为XmlElement类型

                string Name = xe.GetAttribute("Name");

                string type = xe.GetAttribute("Type");

                value = xe.GetAttribute("value");
                if (name == Name)
                {
                    status = int.Parse(type);
                    break;
                }
            }
        }
        catch { }

        return status;

    }
    public void SetSystemInfo(string name, string time)
    {
        XmlDocument doc = new XmlDocument();
        string path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase) + @"\config.xml";
        doc.Load(path);    //加载Xml文件  
        XmlElement rootElem = doc.DocumentElement;   //获取根节点  
        XmlNodeList personNodes = rootElem.GetElementsByTagName("UploadInfo"); //获取PrintInfo 子节点集合  
        foreach (XmlNode node in personNodes)
        {
            XmlElement xe = (XmlElement)node;//将子节点类型转换为XmlElement类型
            if (xe.GetAttribute("Name") == name)
            {
                xe.SetAttribute("value", time);
            }
        }
        doc.Save("config.xml");
    }
    #endregion

    #region 定时执行任务
    public void RegularTasks(int intHour, int intMinute, int intSecond, string url)
    {
        //每十分钟定时执行
        if (intMinute % 10 == 0 && intSecond == 1)
        {
            //UpLoadHykblHData(url);
            // UpLoadHykczjlData(url);
        }


        bool xsDate1 = false;
        bool yyyDate1 = false;
        bool spDate1 = false;

        bool xsDate2 = false;
        bool yyyDate2 = false;
        bool spDate2 = false;

        bool xsDate3 = false;
        bool yyyDate3 = false;
        bool spDate3 = false;


        bool xsDate4 = false;
        bool yyyDate4 = false;
        bool spDate4 = false;


        string value = "";
        int s1 = GetSystemInfo("XSSJ", ref value);

        if (s1 == 1)
        {
            xsDate1 = true;
        }
        else if (s1 == 2)
        {
            xsDate2 = true;
        }
        else if (s1 == 3)
        {
            xsDate3 = true;
        }
        else if (s1 == 4)
        {
            if (value == "" && value == DateTime.Now.ToString("yyyy-MM-dd"))
                xsDate4 = true;
        }


        int s2 = GetSystemInfo("YYYDA", ref value);
        if (s1 == 1)
        {
            yyyDate1 = true;
        }
        else if (s1 == 2)
        {
            yyyDate2 = true;
        }
        else if (s1 == 3)
        {
            yyyDate3 = true;
        }
        else if (s1 == 4)
        {
            if (value == "" && value == DateTime.Now.ToString("yyyy-MM-dd"))
                yyyDate4 = true;
        }

        int s3 = GetSystemInfo("SPDA", ref value);
        if (s3 == 1)
        {
            spDate1 = true;
        }
        else if (s3 == 2)
        {
            spDate2 = true;
        }
        else if (s3 == 3)
        {
            spDate3 = true;
        }
        else if (s3 == 4)
        {
            if (value == "" && value == DateTime.Now.ToString("yyyy-MM-dd"))
                spDate4 = true;
        }
        //每天
        #region  每天一次操作

        string time = DateTime.Now.ToString("yyyy-MM-dd");
        if (xsDate4 && intHour > 11)
        {
            //  UpLoadData();
            SetSystemInfo("XSSJ", time);
        }
        if (yyyDate4 && intHour > 11)
        {
            //   DownloadGetYyyH(url);
            SetSystemInfo("YYYDA", time);

        }
        if (spDate4 && intHour > 11)
        {
            //   DownloadGetCpdaH(url);
            SetSystemInfo("SPDA", time);
        }


        #endregion



        //每小时
        if (intMinute == 58 && intSecond == 58)
        {
            if (xsDate1)
            {
                //  UpLoadData(url);

            }
            if (yyyDate1)
            {
                //  DownloadGetYyyH(url);
            }
            if (spDate1)
            {
                //  DownloadGetCpdaH(url);

            }
        }


        //每分钟
        if (intSecond == 58)
        {
            if (xsDate2)
            {
                //  UpLoadData(url);
            }
            if (yyyDate2)
            {
                //  DownloadGetYyyH(url);
            }
            if (spDate2)
            {
                // DownloadGetCpdaH(url);
            }
        }

        //每秒

        if (xsDate3)
        {
            //  UpLoadData(url);
        }
        if (yyyDate3)
        {
            //    DownloadGetYyyH(url);
        }
        if (spDate3)
        {
            //  DownloadGetCpdaH(url);
        }
    }









    private DataSet FilledDs(DataSet ds, DataTable dt)
    {
        if (ds.Tables.Count > 0)
        {
            object[] obj = new object[dt.Columns.Count];
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                dt.Rows[i].ItemArray.CopyTo(obj, 0);
                ds.Tables[0].Rows.Add(obj);
            }
        }
        else
        {
            DataTable ndt = dt.Copy();
            ds.Tables.Add(ndt);
        }

        return ds;

    }

    #endregion

    #region 序列化 反序列化
    /// 序列化DataTable
    /// </summary>
    /// <param name="pDt">包含数据的DataTable</param>
    /// <returns>序列化的DataTable</returns>
    public static string SerializeDataTableXml(DataTable pDt, string pdtname)
    {
        // 序列化DataTable
        pDt.TableName = pdtname;
        StringBuilder sb = new StringBuilder();
        XmlWriter writer = XmlWriter.Create(sb);
        XmlSerializer serializer = new XmlSerializer(typeof(DataTable));
        serializer.Serialize(writer, pDt);
        writer.Close();
        return sb.ToString();
    }

    ///序列化转化为二进制数组的DataSet
    public byte[] GetDataSetSurrogateZipBYtes(DataSet DS)
    {
        DataSetSurrogate dss = new DataSetSurrogate(DS);
        ///二进制方式方式序列化

        BinaryFormatter ser = new BinaryFormatter();
        MemoryStream ms = new MemoryStream();
        ser.Serialize(ms, dss);
        byte[] buffer = ms.ToArray();
        ///调用压缩方法

        byte[] Zipbuffer = Compress(buffer);
        return Zipbuffer;
    }
    ///压缩二进制文件
    private byte[] Compress(byte[] data)
    {
        MemoryStream ms = new MemoryStream();
        Stream zipStream = null;
        zipStream = new GZipStream(ms, CompressionMode.Compress, true);

        ///从指定的字节数组中将压缩的字节写入基础流

        zipStream.Write(data, 0, data.Length);
        zipStream.Close();
        ms.Position = 0;
        byte[] Compressed_Data = new byte[ms.Length];
        ms.Read(Compressed_Data, 0, int.Parse(ms.Length.ToString()));
        return Compressed_Data;
    }

    ///将压缩后的二进制数组解压
    public static byte[] Decompress(byte[] data)
    {      ///data参数为压缩后的二进制数组
        try
        {
            MemoryStream ms = new MemoryStream(data);
            Stream zipStream = null;
            zipStream = new GZipStream(ms, CompressionMode.Decompress);
            byte[] dc_data = null;
            dc_data = EtractBytesFormStream(zipStream, data.Length);
            return dc_data;

            ///返回解压后的二进制数组
        }
        catch
        {
            return null;
        }
    }

    public static byte[] EtractBytesFormStream(Stream zipStream, int dataBlock)
    {
        try
        {
            byte[] data = null;
            int totalBytesRead = 0;
            while (true)
            {
                Array.Resize(ref data, totalBytesRead + dataBlock + 1);
                int bytesRead = zipStream.Read(data, totalBytesRead, dataBlock);
                if (bytesRead == 0)
                {
                    break;
                }
                totalBytesRead += bytesRead;
            }
            Array.Resize(ref data, totalBytesRead);
            return data;
        }
        catch
        {
            return null;
        }
    }

    /// 将二进制文件反序列化后转化为DataSet
    public DataSet GetDatasetFromByte(byte[] ZipByte)
    {
        byte[] buffer = Decompress(ZipByte);
        BinaryFormatter ser = new BinaryFormatter();
        DataSetSurrogate dss;
        dss = (DataSetSurrogate)ser.Deserialize(new MemoryStream(buffer));
        DataSet DS = dss.ConvertToDataSet();
        return DS;

    }
    /// <summary>
    /// 反序列化DataTable
    /// </summary>
    /// <param name="pXml">序列化的DataTable</param>
    /// <returns>DataTable</returns>
    public DataTable DeserializeDataTable(string pXml)
    {

        StringReader strReader = new StringReader(pXml);
        XmlReader xmlReader = XmlReader.Create(strReader);
        XmlSerializer serializer = new XmlSerializer(typeof(DataTable));

        DataTable dt = serializer.Deserialize(xmlReader) as DataTable;
        return dt;
    }


    #endregion



    /// <summary>
    /// 过滤特殊字符 反SQL注入使用
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    public static bool CheckBadWord(string str)
    {
        string pattern = @"select|insert|delete|from|count\(|drop table|update|truncate|asc\(|mid\(|char\(|xp_cmdshell|exec   master|netlocalgroup administrators|:|net user|""|or|and";
        if (Regex.IsMatch(str, pattern, RegexOptions.IgnoreCase) ) return true;
        return false;
    }
    private static bool ProcessSqlStr(string Str, int type)
    {
        string SqlStr;
        if (type == 1)
            SqlStr = "exec |insert |select |delete |update |count |chr |mid |master |truncate |char |declare ";

        else
            SqlStr = "'|and|exec|insert|select|delete|update|count|*|chr|mid|master|truncate|char|declare";

        bool ReturnValue = true;
        try

        {
            if (Str != "")

            {
                string[] anySqlStr = SqlStr.Split('|');

                foreach (string ss in anySqlStr)
                {
                    if (Str.IndexOf(ss) >= 0)

                    {

                        ReturnValue = false;

                    }
                }
            }

        }

        catch

        {

            ReturnValue = false;

        }

        return ReturnValue;
    }


}


